package com.cloud.consumer.ribbon.service;

import com.cloud.consumer.ribbon.bean.User;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @program: myboots
 * @description:
 * @author: Mr.Zou
 * @create: 2019-08-13 17:44
 **/

@Service
@Slf4j
public class HelloService {

    @Autowired
    private RestTemplate restTemplate;

    // 以下注入负载均衡客户端LoadBalancerClient是一个接口,下面只有一个RibbonLoadBalancerClient实现类
    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Autowired
    private RibbonLoadBalancerClient ribbonLoadBalancerClient;


    @HystrixCommand(fallbackMethod = "hiError")
    public String hiService(String name) {
        log.info("service-ribbon消费了服务");
        String result = restTemplate.getForObject("http://producer/hi?name=" + name, String.class); //自定义 随机方式

        //负载均衡轮询方式请求节点
//        ServiceInstance instance = ribbonLoadBalancerClient.choose("server-producer");
//        log.info("下一次要请求的节点：host:" + instance.getHost() + ",port:" + instance.getPort() + ",serviceId=" + instance.getServiceId() + ",uri=" + instance.getUri());
        return result;
    }

    @HystrixCommand(fallbackMethod = "hiError", commandProperties = {
            @HystrixProperty(name = "xxx", value = "xxx")
    })
    public String bye(String name) {
        log.info("service-ribbon消费了服务");
        return restTemplate.getForObject("http://producer2/hi?name=" + name, String.class);  //默认轮询方式
    }


    public String hiError(String name) {
        return "hi," + name + ",sorry,error!";
    }


    public User getUser(Long id, String name) {
        User user = new User().setId(id).setName(name);
        return restTemplate.postForObject("http://producer/user", user, User.class);
    }


}


